import { ref, onMounted, onUnmounted, computed } from "vue";
import { filter } from "../util/todoStorage";

const validHash = ["all", "active", "completed"];

export default function useFilter(todosRef) { // 这个函数在setup中调用，只会运行一次
  const visibilityRef = ref("all");

  const onHashChange = () => {
    const hash = location.hash.replace(/#\/?/, "");
    if (validHash.includes(hash)) {
      //有效的
      visibilityRef.value = hash;
    } else {
      location.hash = "";
      visibilityRef.value = "all";
    }
  };

  // 1. 组件挂载完成的生命周期函数
  onMounted(() => {
    window.addEventListener("hashchange", onHashChange);
  });
  // 2. 组件销毁过后的生命周期函数，当然这个例子就一个组件，不会销毁
  onUnmounted(() => {
    window.removeEventListener("hashchange", onHashChange);
  });


  // 计算属性是一个ref，还是不完全一样啊，具体后续待研究，反正现在用就和使用ref一样
  // const com = computed({
  //   get() {

  //   },
  //   set(value) {}
  // })


  // 计算属性只有get的情况
  const filteredTodosRef = computed(() => {
    return filter(todosRef.value, visibilityRef.value);
  });

  const remainingRef = computed(() => {
    return filter(todosRef.value, "active").length;
  });

  const completedRef = computed(() => {
    return filter(todosRef.value, "completed").length;
  });

  return {
    visibilityRef,
    filteredTodosRef,
    remainingRef,
    completedRef,
  };
}

